package setting

import (
	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/setting"
	DevcontainersVO "code.gitea.io/gitea/routers/api/devcontainer/vo"
	gitea_context "code.gitea.io/gitea/services/context"
	devstar_devcontainer_service "code.gitea.io/gitea/services/devstar_devcontainer"
	"net/http"
)

const (
	tplSettingsDevContainers base.TplName = "user/settings/dev_containers_list"
)

// ListDevContainers 展示用户所有开发容器
func ListDevContainers(ctx *gitea_context.Context) {

	// 1. 检查页面是否登录，若未登录则重定向到登录页
	ctxUser := ctx.Doer
	if ctxUser == nil {
		ctx.Redirect(setting.AppSubURL + string(setting.LandingPageLogin))
		return
	}

	// 2. 设置前端展示元数据数据
	ctx.Data["Title"] = ctx.Tr("settings.dev_containers_list")
	ctx.Data["PageIsSettingsDevContainersList"] = true

	// 3. 分页查询
	paginationOptions := db.ListOptions{
		PageSize: setting.UI.Admin.DevContainersPagingNum, // 参考 app.ini 配置文件 ui.admin.DEV_CONTAINERS_PAGING_NUM，默认50
		Page:     ctx.FormInt("page"),                     // URL参数起始页码
	}
	if paginationOptions.Page <= 0 {
		paginationOptions.Page = 1
	}
	opts := &DevcontainersVO.SearchUserDevcontainerListItemVoOptions{
		PaginationOptions: paginationOptions,
		Actor:             ctxUser,
	}
	userDevcontainersListVO, err := devstar_devcontainer_service.GetUserDevcontainersList(ctx, opts)
	if err != nil {
		ctx.ServerError("ListDevContainers", err)
		return
	}
	ctx.Data["DevContainers"] = userDevcontainersListVO.DevContainers
	ctx.Data["ContextUser"] = ctxUser
	itemTotalNum := userDevcontainersListVO.ItemTotalNum
	pageTotalNum := userDevcontainersListVO.PageTotalNum
	pageSize := userDevcontainersListVO.PageSize
	currentPage := userDevcontainersListVO.Page
	pager := gitea_context.NewPagination(int(itemTotalNum), pageSize, currentPage, pageTotalNum)
	pager.SetDefaultParams(ctx)
	ctx.Data["Page"] = pager
	ctx.HTML(http.StatusOK, tplSettingsDevContainers)
	return
}
